
//
//  ForgotPSWVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/11/5.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "ForgotPSWVC.h"

@interface ForgotPSWVC ()
@property (weak, nonatomic) IBOutlet UIButton *getMsgBtn;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,assign) int indexURL;
@property (weak, nonatomic) IBOutlet UITextField *phoneAccount;
@property (weak, nonatomic) IBOutlet UITextField *code;
@property (weak, nonatomic) IBOutlet UITextField *psw;
@property (weak, nonatomic) IBOutlet UITextField *checkPSW;
@property(nonatomic,strong) NSString *randomNumber;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@property (weak, nonatomic) IBOutlet UIButton *logInBtn;
@end

@implementation ForgotPSWVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.manager = [AFHTTPSessionManager manager];
    self.getMsgBtn.userInteractionEnabled = NO;
    [self.getMsgBtn setTitleColor:kLabel102Color forState:UIControlStateNormal];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusuccess:) name:@"qingqiusuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusibai:) name:@"qingqiusibai" object:nil];
    self.logInBtn.layer.masksToBounds = YES;
    self.logInBtn.layer.cornerRadius = 6;
}
-(void)qingqiusuccess:(NSNotification *)info
{
    NSString *message = [info.userInfo objectForKey:@"message"];
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSDictionary *date = [dict objectForKey:@"date"];
    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [WSProgressHUD dismiss];
        [self.navigationController popViewControllerAnimated:YES];
    });
}
//-(void)qingqiusibai:(NSNotification *)info
//{
//    NSString *message = [info.userInfo objectForKey:@"message"];
//    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [WSProgressHUD dismiss];
//        if ([message containsString:@"手机"]) {
////            BindVC *vc = [[BindVC alloc]init];
////            vc.openid = self.openid;
////            [self.navigationController pushViewController:vc animated:YES];
//        }else {
//
//        }
//    });
//}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (IBAction)phoneNumTF:(UITextField *)sender {
    if (sender.text.length >= 11) {
//        [sender resignFirstResponder];
        sender.text = [sender.text substringToIndex:11];
        self.getMsgBtn.userInteractionEnabled = YES;
        [self.getMsgBtn setTitleColor:kOrangeBg forState:UIControlStateNormal];
    }else if (sender.text.length < 11) {
        self.getMsgBtn.userInteractionEnabled = NO;
        [self.getMsgBtn setTitleColor:kLabel102Color forState:UIControlStateNormal];
    }
}
- (IBAction)getCodeTF:(UITextField *)sender {
//    if (sender.text.length >= 4) {
//        [sender resignFirstResponder];
//        sender.text = [sender.text substringToIndex:4];
//    }
}
- (IBAction)newPSWTF:(UITextField *)sender {
}
- (IBAction)checkNewPSWTF:(UITextField *)sender {
}
- (IBAction)clickMsgBtn:(UIButton *)sender {
   
    self.indexURL = 9;
    if (![PhoneAndMailCheckObject phoneNumberIsTrue:self.phoneAccount.text]) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"手机号码不正确,请重新输入"];
    }else {
        [self openCountdown];
        self.dict = @{
                      @"phone": self.phoneAccount.text,
                      };
        XLog(@"dict:%@",self.dict);
        self.urlString = [NSString stringWithFormat:@"%@/user/smsSend",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *message = [responseObject objectForKey:@"message"];
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}
#pragma mark-开启倒计时效果
-(void)openCountdown{
    
    int num = (arc4random() % 10000);
    self.randomNumber = [NSString stringWithFormat:@"%.4d", num];
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.getMsgBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                [self.getMsgBtn setTitleColor:kOrangeBg forState:UIControlStateNormal];
                self.getMsgBtn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString *time = [NSString stringWithFormat:@"重新发送(%.2d)", seconds];
                [self.getMsgBtn setTitle:time forState:UIControlStateNormal];
                [self.getMsgBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                self.getMsgBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}
- (IBAction)clickChangePSWBtn:(UIButton *)sender {
//    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"密码需改成功,请登录"];
    if (self.phoneAccount.text.length<11) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入手机号码"];
    }else if (![PhoneAndMailCheckObject phoneNumberIsTrue:self.phoneAccount.text]) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"手机号码不正确,请重新输入"];
    }else if (self.code.text.length == 0) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入验证码"];
    }else if (self.psw.text.length == 0) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入密码"];
    }else if (self.checkPSW.text.length == 0&& ![self.psw.text isEqualToString:self.checkPSW.text]) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"两次输入密码不一样,请重新输入"];
    }else {///user/rePassword
        self.indexURL = 7;
        self.dict = @{
                      @"phone":self.phoneAccount.text,
                      @"code":self.code.text,
                      @"password":self.psw.text,
                      @"confirmPassword":self.checkPSW.text
                      };
        XLog(@"self.dict:%@",self.dict);
        self.urlString = [NSString stringWithFormat:@"%@/user/rePassword",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            NSString *message = [responseObject objectForKey:@"message"];
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                if (self.presentView == 0) {
                    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"密码修改成功,请登录"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                    
                }else {
                    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"密码修改成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self dismissViewControllerAnimated:YES completion:nil];
                    });
                }
                
            }else {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
            }
//            NSString *message = [responseObject objectForKey:@"message"];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            XLog(@"error:%@",error);
        }];
    }
}

@end
